package com.example.vendingmachine.controller;

import com.example.vendingmachine.dto.ProductDTO;
import com.example.vendingmachine.dto.ProductQuery;
import com.example.vendingmachine.entity.Product;
import com.example.vendingmachine.service.ProductService;
import com.example.vendingmachine.common.Result;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 商品管理控制器
 */
@RestController
@RequestMapping("/api/products")
@RequiredArgsConstructor
public class ProductController {

    private final ProductService productService;

    /**
     * 分页查询商品列表
     */
    @GetMapping
    @PreAuthorize("hasAuthority('product:list')")
    public Result<PageInfo<Product>> list(ProductQuery query) {
        return Result.success(productService.listProducts(query));
    }

    /**
     * 获取商品详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('product:list')")
    public Result<Product> getInfo(@PathVariable Long id) {
        return Result.success(productService.getProductById(id));
    }

    /**
     * 新增商品
     */
    @PostMapping
    @PreAuthorize("hasAuthority('product:add')")
    public Result<Long> add(@Validated @RequestBody ProductDTO productDTO) {
        return Result.success(productService.createProduct(productDTO));
    }

    /**
     * 更新商品
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('product:edit')")
    public Result<Void> update(@PathVariable Long id, @Validated @RequestBody ProductDTO productDTO) {
        productDTO.setId(id);
        productService.updateProduct(productDTO);
        return Result.success();
    }

    /**
     * 删除商品
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('product:delete')")
    public Result<Void> delete(@PathVariable Long id) {
        productService.deleteProduct(id);
        return Result.success();
    }

    /**
     * 更新商品状态
     */
    @PutMapping("/{id}/status")
    @PreAuthorize("hasAuthority('product:edit')")
    public Result<Void> updateStatus(@PathVariable Long id, @RequestParam String status) {
        productService.updateProductStatus(id, status);
        return Result.success();
    }

    /**
     * 获取商品总库存
     */
    @GetMapping("/{id}/stock")
    @PreAuthorize("hasAuthority('product:list')")
    public Result<Integer> getTotalStock(@PathVariable Long id) {
        return Result.success(productService.getTotalStock(id));
    }
} 